package flex.cc.wechat.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;

import flex.cc.PublicUtil;
import flex.cc.basicinformation.service.ServiceProviderService;
import flex.cc.common.utils.DateUtil;
import flex.cc.core.annotation.LogAnnotation;
import flex.cc.core.support.BaseController;
import flex.cc.order.manage.dto.order.OrderEvaluateEntity;
import flex.cc.order.manage.dto.order.OrderMainEntity;
import flex.cc.order.manage.dto.vo.OrderMainVo;
import flex.cc.order.manage.service.DownLoadService;
import flex.cc.order.manage.service.OrderEvaluateService;
import flex.cc.order.manage.service.OrderImgService;
import flex.cc.order.manage.service.OrderMainService;
import flex.cc.order.manage.service.OrderPolicyService;
import flex.cc.order.manage.service.OrderRescueService;
import flex.cc.order.manage.service.OrderTrackService;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import flex.cc.vehicle_svr.service.CancelService;
import flex.cc.wechat.entity.WechatUserEntity;
import flex.cc.wechat.service.WechatService;
import flex.cc.wrapper.WrapMapper;
import flex.cc.wrapper.Wrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/vehicleSvr/wechat")
public class WechatController extends BaseController{
	
	@Autowired
    private WechatService wechatService;
    @Autowired
    private DictCodeService dictCodeService;
    @Resource
    private OrderMainService orderMainService;
    @Resource
    private OrderPolicyService orderPolicyService;
    @Resource
    private OrderTrackService orderTrackService;
    @Resource
    private OrderImgService orderImgService;
    @Resource
    private OrderRescueService orderRescueService;
    @Resource
    private DownLoadService downLoadService;
    @Resource
    private ServiceProviderService serviceProviderService;
    @Autowired
    private CancelService cancelService;
    @Autowired
	private OrderEvaluateService orderEvaluateService;
	
    @RequestMapping("/event")
    public void dealWechatEvent(HttpServletRequest request, HttpServletResponse response/*,
    		@RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "signature",required = false) String signature,
            @RequestParam(value = "echostr", required = false) String echostr,
            @RequestBody(required = false) String postData*/) throws IOException {
    	System.out.println("开发接入请求");
    	String echostr=request.getParameter("echostr");
		PrintWriter pw=response.getWriter();
		pw.print(echostr);
		pw.flush();
		pw.close();
		System.out.println("接入成功");
    }
	
	@GetMapping(value = "/dictcode")
    @ApiOperation(httpMethod = "get", value = "查询C端催单次数")
    public Wrapper<Integer> getDictInfo() {
		int urgeCount=3;
		DictCodeEntity codeVo = dictCodeService.searchAllCodeByTypeCode("wechat", "urgeCount", 0, null);
		if(null!=codeVo && null!=codeVo.getValue()) {
			urgeCount=Integer.parseInt(codeVo.getValue());
		}
        return WrapMapper.ok(urgeCount);
    }
	
	@GetMapping(value = "/saveUser/{userid}/{mobile}")
    @ApiOperation(httpMethod = "get", value = "保存用户查询的手机号")
    public Wrapper<Integer> saveUser(@PathVariable String userid,@PathVariable String mobile) {
    	int res=this.wechatService.saveUser(userid, mobile);
        return WrapMapper.ok(res);
    }
    
	@GetMapping(value = "/getUserMobile")
    @ApiOperation(httpMethod = "get", value = "获取当前用户手机号")
    public Wrapper<WechatUserEntity> getUserMobile(@RequestParam String code,@RequestParam String appid) {
    	WechatUserEntity wechatUser=this.wechatService.queryUserMobile(code,appid);
        return WrapMapper.ok(wechatUser);
    }
	
	/**
	 *
	 * @author guozejun
	 * 2021年10月22日下午14:40:41
	 * @desc 服务单分页查询
	 */

   @PostMapping(value = "/queryOrderListInfoPage")
   @ApiOperation(httpMethod = "POST", value = "查询渠道商基本信息")
   public Wrapper<IPage<OrderMainVo>> queryOrderListInfoPage(@ApiParam(name = "orderMainVo", value = "服务单分页信息") @RequestBody OrderMainVo orderMainVo) {
   	IPage<OrderMainVo> result=orderMainService.queryOrderListInfoPage(orderMainVo);
   	return WrapMapper.ok(result);
   }

   /**
	 *
	 * @author guozejun
	 * 2021年10月22日下午14:40:41
	 * @desc 救援详情
	 */
   @LogAnnotation
   @PostMapping(value = "/getRescueDetails")
   @ApiOperation(httpMethod = "POST", value = "转办跳转工单处理页面")
	public Wrapper<OrderMainVo> transferDetail(@RequestBody OrderMainVo vo) {
   	OrderMainVo vo1=orderMainService.getRescueDetails(vo.getOrderNo());
   	return WrapMapper.ok(vo1);
	}
   
   
   @PostMapping(value = "/reminder")
   @ApiOperation(httpMethod = "POST", value = "催单操作")
   public Wrapper<String> reminder(@RequestBody OrderMainVo orderMain){
   	Map<String, Object> result = new HashMap<>();
   	System.out.println(orderMain.getUrgeContent());//催单备注
   	String urgeContent = PublicUtil.isNotEmpty(orderMain.getUrgeContent()) ? orderMain.getUrgeContent() : "";
   	Map<String, Object> postJson = new HashMap<>();
   	postJson.put("orderNo", orderMain.getOrderNo());
    postJson.put("content", urgeContent);
    postJson.put("flag", "0"); //1代表上游的，0代表页面操作的
    postJson.put("oa", "1"); //1代表c端催单
    
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("orderNo", orderMain.getOrderNo());
	OrderMainEntity orderVo = orderMainService.getOneByParams(params);
	String orderStatus = orderVo.getStatus();
	if(orderStatus=="00"||orderStatus=="01"||orderStatus=="08"||orderStatus=="09"||orderStatus=="10"||orderStatus=="11"){
		result.put("responseCode", "01");
       	result.put("responseMsg", "催单失败，服务单状态不满足催单条件");
	}else{
		Map<String, Object> resultMap = orderTrackService.urgeOrder(postJson);
	    String code = (String) resultMap.get("responseCode");
	    if("01".equals(code)){// 催单失败
	    	result.put("responseCode", "01");
	       	result.put("responseMsg", "催单失败！");
	    }else{
	       	result.put("responseCode", "00");
	        result.put("responseMsg", "催单成功！");
	    }
	}
   	return WrapMapper.ok(JSON.toJSONString(result));
   }
   
   @PostMapping(value = "/cancelInfo")
   @ApiOperation(httpMethod = "POST", value = "取消")
   public Wrapper<String> cancelInfo(@RequestBody OrderMainVo orderMain){
   	// 进入接口时间
   	long startTime = System.currentTimeMillis();
   	try {
			logger.info("vehicleSvr/cancelInfo 进入接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
   	 String responseJson = "";
   	 Boolean flag = true;
        String responseMsg = "成功";
        try{
	    	 String result =  cancelService.cancelInfo(orderMain);
	    	 if (result != null) {
	             JSONObject resultObject = JSONObject.parseObject(result);
	
	             System.out.println("resultObject: " + result);
	             Integer resultCode = Integer.valueOf(PublicUtil.isNotEmpty(resultObject.get("resultCode")) ? resultObject.get("resultCode").toString() : null);
	             String message = PublicUtil.isNotEmpty(resultObject.get("message")) ? resultObject.get("message").toString() : null;
	             if (resultCode == 0) {
	                 flag = true;
	                 responseMsg = "取消成功";
	             } else {
	                 flag = false;
	                 responseMsg = message;
	             }
	         } else {
	             flag = false;
	             responseMsg = "取消接口请求异常";
	         }
        }catch(Exception e){
        	e.printStackTrace();
            flag = false;
            responseMsg = "数据接收异常";
        	logger.error("vehicleSvr/cancelOrder 数据接收异常:" + e.getMessage());
        }
        Map<String, String> response = new HashMap<String, String>();
        if(flag){
            response.put("responseCode", "00");
        } else {
            response.put("responseCode", "01");
        }
        response.put("responseMsg", responseMsg);
        responseJson = JSON.toJSONString(response);
        logger.info("vehicleSvr/cancelOrder responseJson:" + responseJson);
      // 离开接口时间
        long endTime = System.currentTimeMillis();
        try {
			logger.info("vehicleSvr/cancelInfo 离开接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + ";处理时长:" + (endTime - startTime));
		} catch (Exception e) {
			e.printStackTrace();
		}
   	return WrapMapper.ok(responseJson);
   }

   /**
	 * response.result.code ==200 时评价成功
	 * */
	@RequestMapping(value = "/evaluate",method= RequestMethod.POST)
   @ApiOperation(value="评价信息保存")
   public Wrapper<Integer> saveEvaluateInfo(@RequestBody OrderEvaluateEntity entity){
		orderEvaluateService.saveEvaluateInfo(entity);
       return  WrapMapper.ok();
  }
}
